package net.pws.oos.web.mobile;

import java.util.List;
import java.util.Map;

import net.pws.common.jackson.JsonUtils;
import net.pws.oos.biz.model.Notice;
import net.pws.oos.biz.query.NoticeFinder;
import net.pws.oos.biz.query.parameter.NoticeQueryParameter;
import net.pws.oos.biz.service.NoticeService;
import net.pws.oos.security.SecurityUtils;
import net.pws.oos.web.NoticeAction;
import net.pws.oos.web.dto.NoticeDto;
import net.pws.oos.web.dto.NoticeNewDto;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/biz/mobile/notice")
@SuppressWarnings("rawtypes")
public class MobileNoticeAction {
    
    private final transient Log logger = LogFactory.getLog(MobileNoticeAction.class);

    @Autowired
    private NoticeFinder noticeFinder;
    
    @Autowired
    private NoticeService noticeService;
    
    @Autowired
    private NoticeAction noticeAction;
    
    @RequestMapping("/list.json")
    @ResponseBody
    public Object myNoticeList(NoticeQueryParameter queryParameter) {
        queryParameter.setReceiverId(SecurityUtils.currentUserId());
        try {
            List<Map> maps = noticeFinder.myList(queryParameter);
            return JsonUtils.succeedMap(NoticeDto.from(maps));
        } catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }

    @RequestMapping("/count.json")
    @ResponseBody
    public Object myNoticeCount(NoticeQueryParameter queryParameter) {
        queryParameter.setReceiverId(SecurityUtils.currentUserId());
        try {
            int count = noticeFinder.myCount(queryParameter);
            return JsonUtils.succeedMap(count);
        } catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }

    @RequestMapping("/read.json")
    @ResponseBody
    public Object readNotice(String id) {
        try {
            Notice notice = noticeFinder.getNotice(id);
            NoticeDto dto = NoticeDto.from(notice);
            noticeService.read(id, SecurityUtils.currentUserId());
            return JsonUtils.succeedMap(dto);
        } catch (Exception e) {
            return JsonUtils.failedMap(e.getMessage());
        }
    }

    @RequestMapping("/create.json")
    @ResponseBody
    public Object createNotice(NoticeNewDto dto) {
        return noticeAction.saveNotice(dto);
    }

}
